﻿using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Infrastructure;
using System.Transactions;

namespace SalesCore.Data.Entity
{
    public class CreateTablesIfNotExist<TContext> : IDatabaseInitializer<TContext> where TContext : DbContextBase
    {
        public void InitializeDatabase(TContext context)
        {
            if (context.DataProviderFactory == null)
            {
                return;
            }

            bool dbExists;
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                dbExists = context.Database.Exists();
            }

            if (dbExists)
            {
                try
                {
                    var dbScript = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
                    if (!string.IsNullOrEmpty(dbScript))
                    {
                        context.DataProviderFactory.CreateTables(dbScript, sql => context.Database.ExecuteSqlCommand(sql), (sql, elementType) => context.Database.SqlQuery(elementType, sql));
                    }
                }
                catch (DbException) { }
                catch (ProviderIncompatibleException) { }
            }
            else
            {
                var defaultInitializer = new CreateDatabaseIfNotExists<TContext>();
                defaultInitializer.InitializeDatabase(context);
            }
        }
    }
}